/**
 * Copyright (c) 2016-2019 九点科技 All rights reserved.
 *
 * http://www.9dyun.cn
 *
 * 版权所有，侵权必究！
 */
package com.dian.modules.fin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.dian.common.exception.RRException;
import com.dian.common.utils.BeanConverter;
import com.dian.common.utils.PUtil;
import com.dian.common.validator.ValidatorUtils;
import com.dian.common.validator.group.AddGroup;
import com.dian.common.validator.group.UpdateGroup;
import com.dian.modules.enums.fin.ReceiDetail_ReceiStateEnum;
import com.dian.modules.fin.vo.ReceiDetailExportVO;
import com.mchange.lang.IntegerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.dian.common.utils.PageUtils;
import com.dian.common.utils.Query;
import com.dian.common.server.CommonService;
import com.dian.modules.fin.dao.ReceiDetailDao;
import com.dian.modules.fin.entity.ReceiDetailEntity;
import com.dian.modules.fin.service.ReceiDetailService;

/**
 * 收款明细单服务实现类
 *
 * @author 赵淼
 * @email 1752060891@qq.com
 * @date 2019-06-15 16:33:49
 */
@Service("receiDetailService")
public class ReceiDetailServiceImpl extends ServiceImpl<ReceiDetailDao, ReceiDetailEntity> implements ReceiDetailService {

    @Autowired
    public CommonService commonService;


    /**
     * 收款明细单分页
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ReceiDetailEntity> page = this.page(new Query<ReceiDetailEntity>().getPage(params), getQueryWrapper(params));
        return new PageUtils(page);
    }

    /**
     * 收款明细单新增
     *
     * @param receiDetailEntity
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean saveInfo(ReceiDetailEntity receiDetailEntity) {

        receiDetailEntity.setReceiNo(commonService.getCode(ReceiDetailEntity.class));
        //数据完整性校验
        this.paramsCheck(receiDetailEntity, AddGroup.class);


        //设置编码，基础默然初始化数据设置
        //receiDetailEntity.setOrderNo(commonService.getOrderCode("XSD"));
        //receiDetailEntity.setOrderDate(new Date());


        //保存
        this.save(receiDetailEntity);

        return true;
    }

    /**
     * 收款明细单更新
     *
     * @param receiDetailEntity
     * @return
     */
    @Override
    public boolean updateInfo(ReceiDetailEntity receiDetailEntity) {

        //修改状态校验
        this.updateCheck(receiDetailEntity.getId());

        //主表数据完整性校验
        this.paramsCheck(receiDetailEntity, UpdateGroup.class);

        //更新主表
        this.updateById(receiDetailEntity);


        return true;
    }

    /**
     * 收款明细单删除
     *
     * @param ids
     * @return
     */
    @Override
    public boolean deleteInfo(Long[] ids) {

        //删除状态校验
        this.deleteCheck(ids);

        //更新主表
        this.remove(new QueryWrapper<ReceiDetailEntity>().in("id", ids));

        return true;
    }

    /**
     * 收款明细单详情
     *
     * @param id
     * @return
     */
    @Override
    public ReceiDetailEntity getInfo(Long id) {
        ReceiDetailEntity receiDetailEntity = getById(id);
        return receiDetailEntity;
    }

    /**
     * 收款明细单审核
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean checkInfo(Long id) {
        ReceiDetailEntity receiDetailEntity = this.getById(id);

        checkCheck(receiDetailEntity);

        receiDetailEntity.setReceiState(ReceiDetail_ReceiStateEnum.AUDITED.getValue());
        receiDetailEntity.setCheckDate(new Date());
        receiDetailEntity.setCheckUserId(commonService.getUserId());
        receiDetailEntity.setCheckUserName(commonService.getUserName());

        //saleOrderHeadEntity.setOrderDate(new Date());
        ///saleOrderHeadEntity.setCheckUserId(commonService.getUserId());
        //saleOrderHeadEntity.setCheckUserName(commonService.getUserName());
        return this.updateById(receiDetailEntity);
    }

    /**
     * 收款明细单作废
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean cancelInfo(Long id) {
        ReceiDetailEntity receiDetailEntity = this.getById(id);
        //验证当前单据状态
        checkCheck(receiDetailEntity);
        //设置单据状态
        receiDetailEntity.setReceiState(ReceiDetail_ReceiStateEnum.INVALID.getValue());
        //修改单据
        return this.updateById(receiDetailEntity);
    }

    /**
     * 收款明细单分页导出
     *
     * @param params
     * @return
     */
    @Override
    public List<ReceiDetailExportVO> exportList(Map<String, Object> params) {
        List<ReceiDetailEntity> list = new ArrayList<>();
        Integer exprotType= PUtil.getParaToInt(params.get("exprotType"),0);
        if (exprotType==0) {
            //导出当前页
            list = this.page(new Query<ReceiDetailEntity>().getPage(params), getQueryWrapper(params)).getRecords();
        } else {
            //导出全部
            list = this.list(getQueryWrapper(params));
        }
        List<ReceiDetailExportVO> resultList = BeanConverter.convertList(list, ReceiDetailExportVO.class);
        return  resultList;
    }

    /***********************************************************************************************/
    /****************************************** 私有方法 ********************************************/
    /***********************************************************************************************/

    /**
     * 修改状态校验
     *
     * @param
     */
    private void updateCheck(Long id) {
        ReceiDetailEntity receiDetailEntity =this.getById(id);
        if (receiDetailEntity.getReceiState().equals(ReceiDetail_ReceiStateEnum.AUDITED.getValue())){
            throw new RRException(String.format("已审核的明细单禁止修改"));
        }
        if (receiDetailEntity.getReceiState().equals(ReceiDetail_ReceiStateEnum.INVALID.getValue())){
            throw new RRException(String.format("已作废的明细单禁止修改"));
        }
        //if(receiDetailEntity.getOrderStat        //    throw new RRException(String.format("已审核的销售订单禁止修改"));e().equals(OrderHead_OrderStateEnum.AUDITED.getValue())){
        //}
    }
    /**
     * 审核状态校验
     *
     * @param
     */
    private void checkCheck(ReceiDetailEntity receiDetailEntity) {
        //已审核
        if (receiDetailEntity.getReceiState().equals(ReceiDetail_ReceiStateEnum.AUDITED.getValue())){
            throw new RRException(String.format("[%s]此收款单已审核",receiDetailEntity.getReceiNo()));
        }
        //已作废
        if (receiDetailEntity.getReceiState().equals(ReceiDetail_ReceiStateEnum.INVALID.getValue())){
            throw new RRException(String.format("[%s]此收款单已作废",receiDetailEntity.getReceiNo()));
        }


    }

    /**
     * 删除状态校验
     *
     * @param ids
     */
    private void deleteCheck(Long[] ids) {
        for (Long id:ids) {
                ReceiDetailEntity receiDetailEntity = this.getById(id);
            if (!receiDetailEntity.getReceiState().equals(ReceiDetail_ReceiStateEnum.WAITCHECK.getValue())){
                throw new RRException(String.format("已审核收款单禁止删除"));
            }
        }


            //if(!saleOrderHeadEntity.getOrderState().equals(OrderHead_OrderStateEnum.WAITCHECK.getValue())){
            //    throw new RRException(String.format("只允许删除未审核的销售订单"));
            //}

    }

    /**
     * 新增和修改参数校验
     *
     * @param record
     */
    private void paramsCheck(ReceiDetailEntity record, Class<?> cls) {
        ValidatorUtils.validateEntity(record, cls);
    }
    /**
     * 获取查询条件
     *
     * @param
     */
    private QueryWrapper<ReceiDetailEntity> getQueryWrapper(Map<String, Object> params) {
        QueryWrapper<ReceiDetailEntity> queryWrapper=new QueryWrapper<>();
        //根据单据编码搜索
        if(!StrUtil.isBlankIfStr(params.get("receiNo"))){
            queryWrapper.like("recei_no",params.get("receiNo"));
        }
        /*if(!StrUtil.isBlankIfStr(params.get("orderCode"))){
            queryWrapper.like("order_code",params.get("orderCode"));
        }*/
        //根据客户编码搜索
        if(!StrUtil.isBlankIfStr(params.get("customerCode"))){
            queryWrapper.like("customer_code",params.get("customerCode"));
        }

        if(!StrUtil.isBlankIfStr(params.get("probId"))){
            queryWrapper.eq("prob_id",params.get("probId"));
        }
        if(!StrUtil.isEmptyIfStr(params.get("propKey"))){
            queryWrapper.and(wrapper -> wrapper
            );
        }


        queryWrapper.orderByAsc("id");
        return queryWrapper;
    }
}
